# @Time : 2024/7/26 10:02
# @Author : Adam
# @Version : v1.0
# @IDE : PyCharm
# @Project : tracer
import os
from django.conf import settings
from django.shortcuts import render, redirect, reverse, HttpResponse
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from web.forms.wiki import WikiModelForm
from web import models

from django.views.decorators.clickjacking import xframe_options_sameorigin


def wiki(request, project_id):
    """wiki的首页"""
    wiki_id = request.GET.get('wiki_id')
    if not wiki_id or not wiki_id.isdecimal():
        return render(request, 'wiki.html')

    wiki_object = models.Wiki.objects.filter(id=wiki_id, project_id=project_id).first()
    return render(request, 'wiki.html', {'wiki_object': wiki_object})


def wiki_add(request, project_id):
    """wiki添加"""
    if request.method == 'GET':
        form = WikiModelForm(request)
        return render(request, 'wiki_form.html', {'form': form})
    form = WikiModelForm(request, data=request.POST)
    if form.is_valid():
        # 判断用户是否已经选择了父文章
        if form.instance.parent:
            form.instance.depth = form.instance.parent.depth + 1
        else:
            form.instance.depth = 1
        # print(form.instance.parent, type(form.instance.parent))
        form.instance.project_id = project_id
        form.save()
        return redirect(reverse('wiki', kwargs={'project_id': project_id}))
    return render(request, 'wiki_form.html', {'form': form})


def wiki_catalog(request, project_id):
    """wiki目录"""
    # 获取当前项目所有的目录:data=QuerySet类型
    data = models.Wiki.objects.filter(project=project_id).values('id', 'title', 'parent_id').order_by('depth', 'id')
    return JsonResponse({'status': True, 'data': list(data)})


# def wiki_detail(request, project_id):
#     """查看文章详细页面
#         /detail?wiki_id=1
#     """
#     return HttpResponse('查看文章详细')

def wiki_delete(request, project_id, wiki_id):
    """删除文章"""
    models.Wiki.objects.filter(project_id=project_id, id=wiki_id).delete()
    return redirect(reverse('wiki', kwargs={'project_id': project_id}))


def wiki_edit(request, project_id, wiki_id):
    """编辑文章"""
    wiki_object = models.Wiki.objects.filter(project_id=project_id, id=wiki_id).first()
    if not wiki_object:
        return redirect(reverse('wiki', kwargs={'project_id': project_id}))
    if request.method == 'GET':
        form = WikiModelForm(request, instance=wiki_object)
        return render(request, 'wiki_form.html', {'form': form})
    form = WikiModelForm(request, data=request.POST, instance=wiki_object)
    if form.is_valid():
        if form.instance.parent:
            form.instance.depth = form.instance.parent.depth + 1
        else:
            form.instance.depth = 1
        form.save()
        url = reverse('wiki', kwargs={'project_id': project_id})
        preview_url = '{0}?wiki_id={1}'.format(url, wiki_id)
        return redirect(preview_url)
    return render(request, 'wiki_form.html', {'form': form})


@csrf_exempt
@xframe_options_sameorigin
def wiki_upload(request, project_id):
    """markdown插件上传图片"""
    print('收到上传的图片了')
    image_object = request.FILES.get('editormd-image-file')
    media_path = os.path.join('media', image_object.name)
    print(media_path)
    with open(media_path, mode='wb') as f:
        for chunk in image_object.chunks():
            f.write(chunk)
    # 文件对象上传到本地目录
    ip_port = request.build_absolute_uri("/")
    result = {
        'success': 1,
        'message': '上传成功',
        'url': ip_port + media_path
    }

    return JsonResponse(result)
